package com.cinco.server.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;

import java.util.Date;
import java.util.UUID;

/**
 * @author cinco
 * @version 1.0
 * @date 2022/1/13
 */
public class JwtTest {
    private long expiration = 60*60*24*1000;
    private String signature  = "admin";

    public String getJwt(){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //payload
                .claim("username","cinco")
                .claim("role","admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return jwtToken;
    }
    public Claims getPayLoad(String jwtToken){
        Claims claims = Jwts.parser()
                .setSigningKey(signature)
                .parseClaimsJws(jwtToken)
                .getBody();
        return claims;
    }

    @Test
    public void test(){
        //生成token
        String jwtToken = this.getJwt();
        System.out.println(jwtToken);

        //从token取出载荷
        Claims claims = getPayLoad(jwtToken);
        System.out.println(claims);
        System.out.println(claims.get("username"));
        System.out.println(claims.get("role"));
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        System.out.println(claims.getExpiration());
    }
}
